package cn.wolfcode.shop.cloud.service.impl;

import cn.wolfcode.shop.cloud.common.BusinessException;
import cn.wolfcode.shop.cloud.domain.OrderInfo;
import cn.wolfcode.shop.cloud.mapper.SeckillOrderInfoMapper;
import cn.wolfcode.shop.cloud.msg.SeckillCodemsg;
import cn.wolfcode.shop.cloud.service.ISeckillGoodService;
import cn.wolfcode.shop.cloud.service.ISeckillOrderInfoService;
import cn.wolfcode.shop.cloud.service.ISeckillOrderService;
import cn.wolfcode.shop.cloud.util.IdGenerateUtil;
import cn.wolfcode.shop.cloud.vo.SeckillGoodVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class SeckillOrderInfoServiceImpl implements ISeckillOrderInfoService {

    @Autowired
    private ISeckillGoodService seckillGoodService;
    @Autowired
    private SeckillOrderInfoMapper seckillOrderInfoMapper;
    @Autowired
    private ISeckillOrderService seckillOrderService;

    @Override
    @Transactional
    public String doSeckill(Long userId, Long seckillId) {
        //减库存
        int count = seckillGoodService.decr(seckillId);
        if (count ==0){
            throw new BusinessException(SeckillCodemsg.SECKILL_STOCKET_OVER);
        }
        //创建出来订单信息保存到数据库中
      String orderNo = createOrderInfo(userId,seckillId);
        //往t_seckill_order去存储一条数据
        seckillOrderService.createSeckillOrder(userId,seckillId,orderNo);
        return orderNo;
    }

    @Override
    public OrderInfo queryByorderNo(String orderNo) {
        return seckillOrderInfoMapper.queryByorderNo(orderNo);
    }

    @Override
    public int changOrderInfoStatus(String orderNo, Integer status) {

        return seckillOrderInfoMapper.changOrderInfoStatus(orderNo,status);
    }

    @Override
    public void changPayStatus(String out_trade_no, Integer status) {
        seckillOrderInfoMapper.changPayStatus(out_trade_no,status);
    }

    private String createOrderInfo(Long userId, Long seckillId) {
        OrderInfo orderInfo = new OrderInfo();
        SeckillGoodVO seckillGoodVO = seckillGoodService.queryById(seckillId);
        orderInfo.setGoodName(seckillGoodVO.getGoodName());
        orderInfo.setGoodImg(seckillGoodVO.getGoodImg());
        orderInfo.setUserId(userId);
        orderInfo.setGoodId(seckillGoodVO.getId());
        orderInfo.setGoodCount(seckillGoodVO.getGoodStock());
        orderInfo.setGoodPrice(seckillGoodVO.getGoodPrice());
        orderInfo.setSeckillPrice(seckillGoodVO.getSeckillPrice());
        orderInfo.setCreateDate(new Date());
        orderInfo.setOrderNo(IdGenerateUtil.get().nextId()+"");
        seckillOrderInfoMapper.save(orderInfo);

        return orderInfo.getOrderNo();
    }
}
